package com.example.assetmanagement.controller;

import com.example.assetmanagement.common.ApiResponse;
import com.example.assetmanagement.service.AttachmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/upload")
@RequiredArgsConstructor
public class AttachmentController {

    private final AttachmentService attachmentService;

    // 上传接口 bizType = asset | maintenance
    @PostMapping
    public ApiResponse<String> upload(@RequestPart("file") MultipartFile file,
                                      @RequestParam(required = false) String bizType) throws IOException {
        String url = attachmentService.upload(file, bizType);
        return ApiResponse.success(url);
    }

    // 下载接口
    @GetMapping
    public void download(@RequestParam String path, HttpServletResponse response) throws IOException {
        byte[] data = attachmentService.download(path);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        String fileName = URLEncoder.encode(path.substring(path.lastIndexOf('/') + 1), StandardCharsets.UTF_8);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        response.getOutputStream().write(data);
    }

    // 删除接口
    @DeleteMapping
    public ApiResponse<?> delete(@RequestParam String path) throws IOException {
        attachmentService.delete(path);
        return ApiResponse.success(null);
    }
} 